﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Security;
using System.Security.Cryptography;
using DataAccessLayer.Login;
using ModelLayer.Login;


namespace ControllerLayer.Login
{
    public class LoginController
    {
        LoginDataAccess logginAccess = new LoginDataAccess();
        User actualUser = User.Instance;
        public static bool autentication = false;
        public static bool exit = false;
     
        public bool VerifyAccessType(int type, string userName, string pwd,int loginTime)
        {
            switch (type)
            {

                case 1:
                    //   actualUser = logginAccess.GetUser(userName);
                    string saltPwd = logginAccess.ReturnSaltPwd(userName);
                    string PasswordSaltedHash_ = ConvertToSaltPassword(pwd, saltPwd);
                    //pero si type=2 borrar user actual y poner nuevo osea desde cero otra vez
                    if (logginAccess.RISAutentification(userName, PasswordSaltedHash_))
                    {
                        if (loginTime == 2) 
                        {
                            actualUser.Reset();
                            this.actualUser = logginAccess.GetUser(userName);
                            autentication = true;
                            return true;
                        }
                        else
                        {
                            actualUser = logginAccess.GetUser(userName);
                            autentication = true;
                         
                            return true;
                        }
                    }
                    else
                    {
                        autentication = false;
                        return false;
                    };
            }
            return false;
        }

        public static User getUserInstanceFromUserName(string userName)
        {
            LoginDataAccess lda = new LoginDataAccess();
            return lda.GetUser(userName);
        }

        private string ConvertToSaltPassword(string pwd, string salt)
        {
            Hash hashSaltedPwd = new Hash();
            hashSaltedPwd.Salt = salt;
            return hashSaltedPwd.Encrypt(pwd);
        }

        public void ResetUser()
        {
            actualUser = null;
        }

        public void UpdateTimeEnter()
        {
            string name = actualUser.getName();
            LoginDataAccess.UpdateLastTimeEnter(name);
        }

        public bool LoginValidate(string p)
        {
            return Validator.InvalidChars(p);
        }

        
    }
}
